import { CLEAR_USER, SET_TOKEN, SET_USER } from './types.js';
import { UserApi } from '@/api/user/api.js';

const getLoginUser = () => {
  return async (dispatch) => {
    const { code, data } = await UserApi.getLoginUser();
    if (code === 0) {
      dispatch({
        type: SET_USER,
        payload: data
      });
    }
  };
};

const setToken = (data) => {
  return {
    type: SET_TOKEN,
    payload: data
  };
};

const logout = () => {
  return async (dispatch) => {
    const { code } = await UserApi.logout();
    if (code === 0) {
      dispatch(clearUser());
    }
  };
};

const clearUser = () => {
  return {
    type: CLEAR_USER
  };
};

export const UserAction = {
  setToken,
  getLoginUser,
  logout,
  clearUser
};
